#include "mythread.h"

QMutex MyThread::mutex;
int MyThread::num = 0;

MyThread::MyThread(QObject* parent):QThread(parent) {}

void MyThread::run()
{
    //1：直接用锁
    // while(true){
    //     QThread::sleep(2); //线程睡眠两秒
    //     this->mutex.lock();
    //     qDebug() << "Current Thread: " << this << ", Value: " << this->num++;
    //     this->mutex.unlock(); //解锁
    // }

    //2：RAII
    while (1)
    {
        //QMutexLocker:创建的时候加锁，当QMutexLocker局部销毁的时候解锁
        {
            QMutexLocker lock(&this->mutex);
            qDebug() << "Current Thread: " << this << ", Value: " << this->num++;
        }
        QThread::sleep(1);// 线程睡眠两秒
    }
}
